//
//  RechargeController.swift
//  Order
//
//  Created by Lazyloading on 2020/7/22.
//  Copyright © 2020 lazyloading. All rights reserved.
//

import UIKit
import ZLPhotoBrowser
import  PKHUD
import PKHUD

/// 充值
class RechargeController: UIViewController {
    
    
    var finishBlock : ((RechargeController)->())?;
    
    @IBOutlet weak var openAccountNickLabel: UILabel!
    @IBOutlet weak var openAccountLabel: UILabel!
    @IBOutlet weak var targetLabel: UILabel!
    @IBOutlet weak var typeLabel: UILabel!
    @IBOutlet weak var accountLabel: UITextField!
    @IBOutlet weak var moneyLabel: UITextField!
    @IBOutlet weak var hintLabel: UILabel!
    @IBOutlet weak var historyImg: UIImageView!
    
    
    
    var codeUrl : String?
    
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    
    
    lazy var addCode: UIButton = {
        let btn = UIButton.init();
        btn.backgroundColor = ZMColor.Orange.orange1;
        btn.addTarget(self, action: #selector(rechargeRequest), for: .touchUpInside);
        btn.layer.cornerRadius = 10;
        btn.layer.masksToBounds = true;
        btn.setTitle("充值成功", for: .normal);
        btn.titleLabel?.font = UIFont.init(fontType: .medium, fontSize: 16);
        return btn;
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.loadDefaultSetting();
        self.initSubViews();
        self.getRechargeInfo();
    }
    
    // MARK: 👉🏻 🐷Life cycle🐷
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews();
        self.topConstraint.constant = ISIPHONEX() ? 120 : 70;
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated);
        if self.finishBlock != nil{
            self.finishBlock!(self);
        }
    }
    // MARK: 👉🏻 🐷System Delegate🐷
    // MARK: 👉🏻 🐷Custom Delegate🐷
    // MARK: 👉🏻 🐷Event  Response🐷
    @objc func selectImage(tap : UITapGestureRecognizer){
        weak var weakSelf = self;
        let actioinSheet = ZLPhotoActionSheet.init();
        actioinSheet.configuration.maxSelectCount = 1;
        actioinSheet.configuration.maxPreviewCount = 10;
        actioinSheet.sender = self;
        actioinSheet.selectImageBlock = {images,assets,isOriginal in
            weakSelf?.uploadImage(image: (images?.first)!);
            weakSelf?.historyImg.image = images?.first;
        };
        actioinSheet.showPreview(animate: true);

        ZMLog("选择照片");
    }
    func uploadImage(image : UIImage) {
        weak var weakSelf = self;

        HUD.show(.label("上传中......"))
        MoyaRequest(.uploadData([image]), success: { (response  :  BaseResponse<[String : Any]>) in
            HUD.hide();
            if response.respCode == 200{
                weakSelf!.codeUrl = (response.data!["fileName"] as! String);
            }else{
                HUD.flash(.label("上传失败"),delay: 1);
            }
        }) { (error) in
            HUD.hide();
            HUD.flash(.label("上传失败"),delay: 1);
        }
    }
    // MARK: 👉🏻 🐷Private Methods🐷
    @objc func rechargeRequest() {
        
        if  self.moneyLabel.text?.count == 0 {
            HUD.flash(.label("请输入充值金额"),delay: 1)
            return;
        }
        
        if  self.moneyLabel.text?.count == 0 {
            HUD.flash(.label("请输入转出账户"),delay: 1)
            return;
        }
        
        
        let param = [
            "receiptAccount" : self.targetLabel.text ?? "",
            "receiptType" : self.typeLabel.text ?? "",
            "rechargeAmount" : self.moneyLabel.text ?? "",
            "transferOutAccount" : self.accountLabel.text ?? "",
            "voucherUrl" : self.codeUrl ?? ""
        ];
        weak var weakSelf = self;

        MoyaRequest(.recharge(param), success: { (response : BaseResponse<[String : Any]>) in
            if response.respCode == 200{
                HUD.flash(.label("充值信息提交成功"),delay: 1)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                    weakSelf?.navigationController?.popViewController(animated: true);
                }
            }else{
                
            }
        }) { (error) in
            
        }
    }
    
    ///获取收款信息
    func getRechargeInfo()  {
        weak var weakSelf = self;
        MoyaRequest(.getRechargeInfo, success: { (response : BaseResponse<[String : Any]>) in
            if response.respCode == 200{
                weakSelf?.targetLabel.text = (response.data!["payAccount"] as! String);
                weakSelf?.typeLabel.text = (response.data!["payMethod"] as! String);
                let remark  = (response.data!["remark"] as! String);
                if remark.count > 0 {
                    
                    weakSelf?.openAccountNickLabel.text =  remark;
                    weakSelf?.openAccountNickLabel.isHidden =  false;
                    weakSelf?.openAccountLabel.isHidden =  false;
                }else{
                    weakSelf?.openAccountNickLabel.text =  "";
                    weakSelf?.openAccountNickLabel.isHidden =  true;
                    weakSelf?.openAccountLabel.isHidden =  true;
                }
                
            }else{
                HUD.flash(.label("充值信息获取失败"),delay: 1);
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                    weakSelf?.navigationController?.popViewController(animated: true);
                }
            }
        }) { (error) in
            HUD.flash(.label("充值信息获取失败"),delay: 1);
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                weakSelf?.navigationController?.popViewController(animated: true);
            }

        }
    }
    // MARK: 👉🏻 🐷Lazy loading🐷
    // MARK: 👉🏻 🐷Init SubViews🐷
    func loadDefaultSetting()  {
        self.navigationItem.title = "充值";
        self.view.backgroundColor = .white;
        self.historyImg.layer.borderColor = ZMColor.Black.black1.cgColor;
        self.historyImg.layer.borderWidth = 0.8;
        self.historyImg.contentMode = .center;
    }
    func initSubViews()  {
        
        self.historyImg.isUserInteractionEnabled = true;
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(selectImage(tap:)));
        self.historyImg.addGestureRecognizer(tap);
        
        
        self.view.addSubview(self.addCode);
        self.layout();
        
    }
    
    func layout() {
        
        self.addCode.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().offset(20);
            make.trailing.equalToSuperview().offset(-20);
            make.height.equalTo(50);
            make.bottom.equalToSuperview().offset(-SafeBottom_H-25);
        };
    }
}
